/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewApplication.java
 *
 * Created on 2010-5-8, 14:15:03
 */
package com.XSQS.util;

import com.XSQS.storage.util.DocItem;
import com.XSQS.xmlQueryEngine.ResultList;
import com.XSQS.xmlQueryEngine.exceptions.InvalidQueryException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.ListModel;

/**
 *
 * @author KuangZimin
 */
public class NewApplication extends javax.swing.JFrame {

    /** Creates new form NewApplication */
    public NewApplication() {
        initComponents();
        initEngine();
        initData();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jSplitPaneFrame = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListDocuments = new javax.swing.JList();
        jTabbedPaneEditor = new javax.swing.JTabbedPane();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        openMenuItem = new javax.swing.JMenuItem();
        saveMenuItem = new javax.swing.JMenuItem();
        saveAsMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        cutMenuItem = new javax.swing.JMenuItem();
        copyMenuItem = new javax.swing.JMenuItem();
        pasteMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentsMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("XSQS Management Studio");
        setMinimumSize(new java.awt.Dimension(800, 600));

        jToolBar1.setRollover(true);

        jButton1.setText("New");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        jButton2.setText("Execute");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        jButton3.setText("Rollback");
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton3);

        jSplitPaneFrame.setDividerLocation(300);

        jListDocuments.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jListDocuments);

        jSplitPaneFrame.setLeftComponent(jScrollPane1);
        jSplitPaneFrame.setRightComponent(jTabbedPaneEditor);

        fileMenu.setText("File");

        openMenuItem.setText("Open");
        fileMenu.add(openMenuItem);

        saveMenuItem.setText("Save");
        fileMenu.add(saveMenuItem);

        saveAsMenuItem.setText("Save As ...");
        fileMenu.add(saveAsMenuItem);

        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setText("Edit");

        cutMenuItem.setText("Cut");
        editMenu.add(cutMenuItem);

        copyMenuItem.setText("Copy");
        editMenu.add(copyMenuItem);

        pasteMenuItem.setText("Paste");
        editMenu.add(pasteMenuItem);

        deleteMenuItem.setText("Delete");
        editMenu.add(deleteMenuItem);

        menuBar.add(editMenu);

        helpMenu.setText("Help");

        contentsMenuItem.setText("Contents");
        helpMenu.add(contentsMenuItem);

        aboutMenuItem.setText("About");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPaneFrame, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPaneFrame, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void initEngine() {
        m_engine = new com.XSQS.xmlQueryEngine.XQEngine();
        m_engine.setMinIndexableWordLength(0);
        m_engine.setShowFileIndexing(true);
        m_engine.setUseLexicalPrefixes(true);
        m_engine.setIndexer();
    }

    private void initData() {
        docItems = new com.XSQS.storage.manager.DocItems();
        ArrayList<DocItem> docItemList = docItems.getAllItems();
        DefaultListModel model = new DefaultListModel();
        jListDocuments.setModel(model);
        for (int i = 0; i < docItemList.size(); i++) {
            model.addElement(docItemList.get(i).getDocName());
        }
    }

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        JTextArea jTextArea1 = new JTextArea();
        JTextArea jTextArea2 = new JTextArea();
        JTextArea jTextArea3 = new JTextArea();
        taList.add(jTextArea1);
        taList.add(jTextArea2);
        taList.add(jTextArea3);
        JTabbedPane jTabbedPane1 = new JTabbedPane();
        jTabbedPane1.add(new JScrollPane(jTextArea2));
        jTabbedPane1.add(new JScrollPane(jTextArea3));
        jTabbedPane1.setTitleAt(0, "Result");
        jTabbedPane1.setTitleAt(1, "Message");
        JSplitPane jSplitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(jTextArea1), jTabbedPane1);
        jSplitPane1.setDividerLocation(200);
        jTabbedPaneEditor.add(jSplitPane1);
        jTabbedPaneEditor.setTitleAt(jTabbedPaneEditor.getTabCount() - 1, "query" + queryCount++);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        int selectedIndex = jTabbedPaneEditor.getSelectedIndex();
        String queryStr = getQueryString(selectedIndex);
        ResultList results = null;
        JTextArea[] jTextArea1 = getOutputTextAreas(selectedIndex);
        try {
            results = m_engine.setQuery(queryStr);
        } catch (InvalidQueryException ex) {
            jTextArea1[1].setText("invalid query");
            ((JTabbedPane) ((JSplitPane) jTabbedPaneEditor.getSelectedComponent()).getBottomComponent()).setSelectedIndex(1);
        }
        if (results == null || results.getNumValidItems() == 0) {
            jTextArea1[1].setText("no hits");
            ((JTabbedPane) ((JSplitPane) jTabbedPaneEditor.getSelectedComponent()).getBottomComponent()).setSelectedIndex(1);
        } else {
            jTextArea1[1].setText("total " + results.getNumValidItems() + " result(s)");
            jTextArea1[0].setText(results.emitXml());
            ((JTabbedPane) ((JSplitPane) jTabbedPaneEditor.getSelectedComponent()).getBottomComponent()).setSelectedIndex(0);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed

    private String getQueryString(int selectedIndex) {
        JTextArea jTextArea1 = taList.get(selectedIndex * 3);
        String queryStr = jTextArea1.getSelectedText();
        if (queryStr == null || queryStr.equals("")) {
            queryStr = jTextArea1.getText();
        }
        return queryStr;
    }

    private JTextArea[] getOutputTextAreas(int selectedIndex) {
        JTextArea[] jTextArea1 = new JTextArea[2];
        jTextArea1[0] = taList.get(selectedIndex * 3 + 1);
        jTextArea1[1] = taList.get(selectedIndex * 3 + 2);
        return jTextArea1;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewApplication().setVisible(true);
            }
        });
    }
    private com.XSQS.xmlQueryEngine.XQEngine m_engine;
    private com.XSQS.storage.manager.DocItems docItems;
    private int queryCount = 1;
    private ArrayList<JTextArea> taList = new ArrayList<JTextArea>();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JMenuItem contentsMenuItem;
    private javax.swing.JMenuItem copyMenuItem;
    private javax.swing.JMenuItem cutMenuItem;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JList jListDocuments;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPaneFrame;
    private javax.swing.JTabbedPane jTabbedPaneEditor;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JMenuItem pasteMenuItem;
    private javax.swing.JMenuItem saveAsMenuItem;
    private javax.swing.JMenuItem saveMenuItem;
    // End of variables declaration//GEN-END:variables
}
